package me.sealer.ssm.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import me.sealer.ssm.constant.Dict;
import me.sealer.ssm.constant.RoleConstant;
import me.sealer.ssm.controller.dto.CommonResponse;
import me.sealer.ssm.controller.dto.QueryPermissionsResponse;
import me.sealer.ssm.controller.dto.RolePermissionsModifyRequest;
import me.sealer.ssm.model.Permission;
import me.sealer.ssm.service.PermissionService;
import me.sealer.ssm.service.RolePermissionService;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author sealer
 * @date 2016/09/27
 */
@Slf4j
@RestController
@Api(tags = "角色权限管理相关api")
@RequestMapping("/rolePermissionMgmt")
@RequiresRoles(value = {RoleConstant.ROLE_ADMIN})
public class RolePermissionMgmtController {
    private final PermissionService permissionService;
    private final RolePermissionService rolePermissionService;

    public RolePermissionMgmtController(PermissionService permissionService, RolePermissionService rolePermissionService) {
        this.permissionService = permissionService;
        this.rolePermissionService = rolePermissionService;
    }

    @GetMapping("/permission/{roleName}")
    @ApiOperation(value = "查询角色对应的所有权限")
    public CommonResponse<QueryPermissionsResponse> queryPermissions(@ApiParam(value = "角色名", required = true) @PathVariable(value = Dict.ROLE_NAME) String roleName) {

        // having permissions
        List<Permission> havingPermissions = rolePermissionService.queryPermissionsByRoleName(roleName);
        List<Integer> havingPermissionsIds = havingPermissions.stream().map(Permission::getId).collect(Collectors.toList());

        // all permissions
        List<Permission> allPermissions = permissionService.queryAllPermissions();
        return new CommonResponse<>(new QueryPermissionsResponse(roleName, havingPermissionsIds, allPermissions));
    }

    @ApiOperation(value = "修改角色权限")
    @PostMapping(value = "/modify", produces = MediaType.APPLICATION_JSON_VALUE)
    public CommonResponse modify(@Valid @RequestBody RolePermissionsModifyRequest rolePermissionsModifyRequest) {

        String roleName = rolePermissionsModifyRequest.getRoleName();
        List<Integer> permissionsIds = rolePermissionsModifyRequest.getPermissions();
        rolePermissionService.modifyRolePermissions(roleName, permissionsIds);
        return new CommonResponse();
    }
}
